<?php

namespace App\Common\WX\App;


use App\Common\Log;
use App\Common\OA\OA;
use App\Common\WX\Api\msg48\Entity\NewItem;
use App\Common\WX\Api\msg48\Entity\News;
use App\Common\WX\WxWord;
use App\Model\t_wx_reply;
use XWX\Common\H;

class WxAppCommon extends WxAppBase
{
    public function funcHandle(WxWord $word, $wx_from)
    {
        Log::funcLogDebug(__METHOD__, '通用处理');


        $entity_reply = null;

        $app_id = $word->app();
        $key = $word->keyNum();
        if (is_numeric($word->content()))
        {
            $app_id = 'reply';

            $key = $word->content();
        }


        if (H::funcStrStartsWith($word->suffix(), "id:"))
        {
            //根据ID
            $reply_id = explode(':', $word->suffix())[1];
            $entity_reply = t_wx_reply::funcGet($this->context()->db(), $reply_id);
        }


        if ($entity_reply == null)
        {
            //尝试找key
            $entity_reply = t_wx_reply::funcReplyApp($app_id, $key);
        }


        $official_account = $this->getOfficialAccount();

        if ($entity_reply !== null)
        {
            switch ($entity_reply->reply_type)
            {
                case 'text':
                    $official_account->msg48()->funcSendText($wx_from, $entity_reply->reply_desc);
                    break;

                case 'msg':
                    $item = new NewItem();
                    $item->title = $entity_reply->reply_title;
                    $item->picurl = OA::funcGetFileUrl($entity_reply->reply_pic);
                    $item->description = $entity_reply->reply_desc;
                    $item->url = $entity_reply->getRedirect();

                    $news = new News();
                    $news->touser = $wx_from;
                    $news->addNewItem($item);

                    $official_account->msg48()->funcSendNews($news);
                    break;
            }
        }
    }
}